from flask import request
from flask_classy import FlaskView, route

from payment.services.fund_channel import FundChannelService
from payment.services.trade import TradeService
from ..models.order import Order
from ..schema.param import create_payment_param
from ..schema.resp import payment_result
from ..services.order import OrderService


class OrdersView(FlaskView):
    @route('/merge_payment', methods=['POST'])
    def create_payment(self):
        data, errors = create_payment_param.load(request.get_json())

        channel_id = data.pop('channel')

        channel = FundChannelService.get_channel_by_id(channel_id)

        if not channel:
            # TODO 报错
            pass

        order_ids = data.pop('order_id')
        order_list = []
        body = 'DGM商城订单'
        for order_id in order_ids:
            order = OrderService.get_order_by_id(order_id)
            if not order:
                # TODO 报错
                pass
            if not order.status != Order.STATUS_WAIT_PAY:
                # TODO 订单状态不对，报错
                pass
            body = body + '# ' + order_id
            order_list.append(order)
        # 每个订单都创建一条支付流水
        payment_trade = []
        # payment_seq = self._gen_payment_seq()
        for order in order_list:
            trade_order = TradeService.create_fundin_trade(
                fund_channel=channel,
                amount=order.amount,
                currency=order.currency_id,
                trade_code=str(order.id).zfill(20),
                description=order.description
            )
            # order.payment_seq = payment_seq
            order.payment_method = channel.id
            order.trade_id = trade_order.id

            payment_trade.append(trade_order)
        payment_response = TradeService.merge_payment(payment_trade, fund_channel=channel,
                                                      currency='CNY',
                                                      body=body,
                                                      return_url=data.get('return_url', None),
                                                      payment_type='fundin')
        for order in order_list:
            order.payment_seq = payment_response.order_no
        return payment_result.jsonify(payment_response)

    def _gen_payment_seq(self):
        import datetime
        return datetime.datetime.now().strftime('%y%j%H%M%S')
